/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.transaction;

import java.util.ArrayList;
import java.util.List;

import org.zhiqim.kernel.model.maps.HashMapSO;
import org.zhiqim.kernel.model.maps.HashMapSV;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Asserts;

/**
 * 事务管理类，提供默认读ORM服务生成事务，以及指定生成事务方法
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class TransactionManager
{
    private static final HashMapSV<TransactionService> serviceMap = new HashMapSV<>();
    private static final ThreadLocal<HashMapSO> variableMap = new ThreadLocal<>();

    /** 判断是否已添加事务服务 */
    public static boolean hasTransactionService(String id)
    {
        return serviceMap.containsKey(id);
    }
    
    /** 添加事务服务 */
    public static void addTransactionService(TransactionService service)
    {
        serviceMap.put(service.getId(), service);
    }
    
    /** 移除事务服务 */
    public static void removeTransactionService(String id)
    {
        serviceMap.remove(id);
    }

    /** 移除事务服务 */
    public static void removeTransactionService(TransactionService service)
    {
        serviceMap.remove(service.getId());
    }
    
    /** 开始单个事务，指定事务编号 */
    public static Transaction beginTransaction(String id) throws Exception
    {
        Asserts.notEmptyBlank(id, "事务服务编号不能为空白");
        TransactionService service = serviceMap.get(id);
        Asserts.as(service != null?null:"根据[%s]未找到事务服务", id);
        
        HashMapSO instanceMap = variableMap.get();
        if (instanceMap == null)
        {
            instanceMap = new HashMapSO();
            variableMap.set(instanceMap);
        }
        
        Object instance = instanceMap.get(id);
        if(instance == null) 
        {
            instance = service.getTransactionInstance();
            instanceMap.put(id, instance);
        }
        
        return service.beginTransaction(instance);
    }
    
    /**
     * 开始事务，指定多个事务编号
     * 
     * @param ids           事务编号字符串，多个用逗号隔开
     * @return Transaction  得到事务
     * @throws Exception    异常
     */
    public static Transaction beginTransactions(String ids) throws Exception
    {
        String[] idArr = Arrays.toStringArray(ids);
        return beginTransaction(idArr);
    }
    
    /**
     * 开始事务，指定事务编号数组
     * 
     * @param ids           事务编号数组
     * @return Transaction  得到事务
     * @throws Exception    异常
     */
    public static Transaction beginTransaction(String... ids) throws Exception
    {
        if (ids == null || ids.length == 0)
        {//未传参数表示所有
            ids = serviceMap.keySet().toArray(new String[0]);
        }
        
        List<Transaction> txList = new ArrayList<>();
        for (String id : ids)
        {
            txList.add(beginTransaction(id));
        }
        
        return new TransactionLister(ids, txList);
    }
    
    /** 获取事务中的实例 */
    public static Object getInstance(String id)
    {
        HashMapSO instanceMap = variableMap.get();
        if (instanceMap == null)
            return null;
        
        return instanceMap.get(id);
    }
    
    /** 关闭指定事务 */
    public static void closeTransaction(String... ids)
    {
        if (ids == null || ids.length == 0)
        {
            variableMap.set(null);
            return;
        }
        
        HashMapSO instanceMap = variableMap.get();
        if (instanceMap == null)
            return;
        
        for (String id : ids)
            instanceMap.remove(id);
        
        //最后一个清空
        if (instanceMap.isEmpty())
            variableMap.set(null);
    }
}
